package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor{
    
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         *  登录拦截检查
         */
        //1. 获取当前的请求方法, 静态资源不属于HandlerMethod
        UserInfo user = null;
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod)handler;
            //2. 判断该方法是否贴有@RequireLogin
            String token = CookieUtil.getToken(request, response);
            String userStr = userInfoRedisService.getToken(token);
            user = JSON.parseObject(userStr, UserInfo.class);
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                //3. 有则需要登录检查
                if(user == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        request.getSession().setAttribute("userInfo",user);
        //4.否则放行
        return true;
    }
}
